package com.sc.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sc.admin.common.annotation.Log;
import com.sc.admin.common.enums.BusinessTypeEnum;
import com.sc.admin.common.enums.ModuleEnum;
import com.sc.admin.common.result.PageResult;
import com.sc.admin.common.result.Result;
import com.sc.admin.common.util.ExcelUtils;
import com.sc.admin.model.entity.sys.SysUser;
import com.sc.admin.model.form.UserForm;
import com.sc.admin.model.form.UserInfoForm;
import com.sc.admin.model.form.UserPasswordForm;
import com.sc.admin.model.query.UserPageQuery;
import com.sc.admin.model.vo.*;
import com.sc.admin.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.sc.admin.plugin.easyexcel.UserImportListener;
import com.sc.admin.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 用户控制器
 *
 * @author shen chen
 * @since 2022/10/16
 */
@Tag(name = "02.用户接口")
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService userService;

    @Operation(summary = "用户分页列表")
    @GetMapping("/page")
    public PageResult<UserPageVO> getUserPage(@ParameterObject UserPageQuery queryParams) {
        IPage<UserPageVO> result = userService.getUserPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "用户表单数据")
    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(@Parameter(description = "用户ID") @PathVariable Long userId) {
        UserForm formData = userService.getUserFormData(userId);
        return Result.success(formData);
    }

    @Operation(summary = "用户个人数据")
    @GetMapping("/userPersonInfo")
    public Result<UserPersonInfoVO> getUserPersonInfo() {
        return Result.success(userService.getUserPersonInfo());
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @SaCheckPermission("sys:user:add")
    @PreventDuplicateSubmit
    @Log(module = ModuleEnum.USER, title = "新增用户", businessType = BusinessTypeEnum.UPDATE)
    public Result saveUser(@RequestBody @Valid UserForm userForm) {
        boolean result = userService.saveUser(userForm);
        return Result.judge(result);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/{userId}")
    @SaCheckPermission("sys:user:edit")
    @Log(module = ModuleEnum.USER, title = "修改用户", businessType = BusinessTypeEnum.UPDATE)
    public Result updateUser(@Parameter(description = "用户ID") @PathVariable Long userId, @RequestBody @Validated UserForm userForm) {
        boolean result = userService.updateUser(userId, userForm);
        return Result.judge(result);
    }


    @Operation(summary = "修改个人信息")
    @PatchMapping(value = "/userInfo")
    @Log(module = ModuleEnum.USER, title = "修改个人信息", businessType = BusinessTypeEnum.UPDATE)
    public Result<Boolean> updateUserInfo(@RequestBody @Validated UserInfoForm userForm) {
        boolean result = userService.updateUserInfo(userForm);
        return Result.judge(result);
    }

    @Operation(summary = "修改个人密码")
    @PatchMapping(value = "/password")
    @Log(module = ModuleEnum.USER, title = "修改个人密码", businessType = BusinessTypeEnum.UPDATE)
    public Result<Void> updatePassword(@RequestBody @Validated UserPasswordForm passwordForm) {
        return userService.updatePassword(passwordForm);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    @SaCheckPermission("sys:user:delete")
    @Log(module = ModuleEnum.USER, title = "删除用户", businessType = BusinessTypeEnum.DELETE)
    public Result deleteUsers(@Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = userService.deleteUsers(ids);
        return Result.judge(result);
    }

    @Operation(summary = "修改用户密码")
    @PatchMapping(value = "/{userId}/password")
    @SaCheckPermission("sys:user:password:edit")
    @Log(module = ModuleEnum.USER, title = "修改用户密码", businessType = BusinessTypeEnum.UPDATE)
    public Result updatePassword(@Parameter(description = "用户ID") @PathVariable Long userId, @RequestParam String password) {
        boolean result = userService.updatePassword(userId, password);
        return Result.judge(result);
    }

    @Operation(summary = "修改用户状态")
    @PatchMapping(value = "/{userId}/status")
    @Log(module = ModuleEnum.USER, title = "修改用户状态", businessType = BusinessTypeEnum.UPDATE)
    public Result updateUserStatus(@Parameter(description = "用户ID") @PathVariable Long userId, @Parameter(description = "用户状态(1:启用;0:禁用)") @RequestParam Integer status) {
        boolean result = userService.update(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getId, userId).set(SysUser::getStatus, status));
        return Result.judge(result);
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        UserInfoVO userInfoVO = userService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入用户")
    @PostMapping("/_import")
    @Log(module = ModuleEnum.USER, title = "导入用户", businessType = BusinessTypeEnum.IMPORT)
    public Result importUsers(@Parameter(description = "部门ID") Long deptId, MultipartFile file) throws IOException {
        UserImportListener listener = new UserImportListener(deptId);
        String msg = ExcelUtils.importExcel(file.getInputStream(), UserImportVO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出用户")
    @GetMapping("/_export")
    @Log(module = ModuleEnum.USER, title = "导出用户", businessType = BusinessTypeEnum.EXPORT)
    public void exportUsers(UserPageQuery queryParams, HttpServletResponse response) throws IOException {
        List<UserExportVO> exportUserList = userService.listExportUsers(queryParams);
        ExcelUtils.export(response, UserExportVO.class, exportUserList, "用户列表");
    }


}
